<!-- PdfViewerModal.vue -->
<template>
    <van-popup v-model:show="showPopup" position="bottom" :style="{ height: '90%' }">
        <div class="pdf-viewer-header">
            <van-nav-bar :title="props.title" left-text="返回" @click-left="close">
                <template #right>
                    <van-icon name="down" @click="download" />
                </template>
            </van-nav-bar>
        </div>
        <div class="pdf-container">
            <div class="page-tool">
                <div class="page-tool-item" @click="lastPage">上一页</div>
                <div class="page-tool-item">
                    {{ state.pageNum }} / {{ state.numPages }}
                </div>
                <div class="page-tool-item" @click="nextPage">下一页</div>
                <!-- <div class="page-tool-item" @click="pageZoomOut" v-show="false">放大</div>
                <div class="page-tool-item" @click="pageZoomIn" v-show="false">缩小</div> -->
            </div>
            <div v-if="!state.numPages" class="loading-state">
                <van-loading type="spinner" size="20px">加载中,文件比较大,请耐心等待...</van-loading>
            </div>
            <div class="pdf-preview">
                <div class="pdf-wrap" ref="pdfWrapRef" @scroll="handleScroll">
                    <VuePdfEmbed v-if="props.pdfUrl && !state.renderAllPages" :source="props.pdfUrl"
                        :page="state.pageNum" :scale="state.scale" @loaded="handleDocumentLoad" class="vue-pdf-embed" />

                    <!-- 多页连续渲染模式 会导致页面卡顿默认不显示-->
                    <div v-if="props.pdfUrl && state.renderAllPages" class="multi-page-container">
                        <VuePdfEmbed v-for="page in displayedPages" :key="page" :source="props.pdfUrl" :page="page"
                            :scale="state.scale" @loaded="handleMultiPageLoad(page, $event)"
                            class="vue-pdf-embed multi-page" />
                    </div>
                </div>
            </div>
        </div>
    </van-popup>
</template>

<script setup lang="ts">
import { reactive, computed, ref } from "vue";
import { defineAsyncComponent } from 'vue'

const VuePdfEmbed = defineAsyncComponent(() =>
    import('vue-pdf-embed')
)
const props = withDefaults(defineProps<{
    pdfUrl?: string;
    title?: string;
}>(), {
    pdfUrl: '',
    title: '报告预览'
});

const emit = defineEmits<{
    (e: 'download'): void;
}>();

const showPopup = ref(false);

const open = () => {
    showPopup.value = true;
};

// 添加pdf容器引用
const pdfWrapRef = ref<HTMLElement | null>(null);

const state = reactive({
    pageNum: 1,
    scale: 1,
    numPages: 0,
    renderAllPages: false, // 默认启用多页渲染
    maxPages: 5, // 初始渲染页面数
    loadedPages: 5, // 已加载的页面数
    loadingMore: false // 是否正在加载更多
});

// 计算需要显示的页面
const displayedPages = computed(() => {
    if (!state.renderAllPages) return [];
    // 如果numPages还未设置，先返回已加载的页面
    if (!state.numPages) {
        return Array.from({ length: Math.min(state.loadedPages, state.maxPages) }, (_, i) => i + 1);
    }
    return Array.from({ length: Math.min(state.numPages, state.loadedPages) }, (_, i) => i + 1);
});

// 处理滚动事件
function handleScroll() {
    if (!pdfWrapRef.value || state.loadingMore || !state.numPages) return;

    const { scrollTop, scrollHeight, clientHeight } = pdfWrapRef.value;
    // 当滚动到底部附近时加载更多
    if (scrollTop + clientHeight >= scrollHeight - 100) {
        loadMorePages();
    }
}

// 加载更多页面
function loadMorePages() {
    if (state.loadingMore || !state.numPages || state.loadedPages >= state.numPages) return;

    state.loadingMore = true;
    // 每次增加5页，但不超过总页数
    state.loadedPages = Math.min(state.loadedPages + 5, state.numPages);

    // 模拟加载延迟，实际项目中可根据需要调整
    setTimeout(() => {
        state.loadingMore = false;
    }, 300);
}

function lastPage() {
    if (state.pageNum > 1) {
        state.pageNum -= 1;
    }
}

function nextPage() {
    if (state.pageNum < state.numPages) {
        state.pageNum += 1;
    }
}

// function pageZoomOut() {
//     if (state.scale < 2) {
//         state.scale += 0.1;
//     }
// }

// function pageZoomIn() {
//     if (state.scale > 0.1) {
//         state.scale -= 0.1;
//     }
// }

function handleDocumentLoad(pdf: any) {
    state.numPages = pdf.numPages;
    // 如果初始加载的页面数超过了总页数，则调整为总页数
    if (state.loadedPages > state.numPages) {
        state.loadedPages = state.numPages;
    }
}

function handleMultiPageLoad(page: number, pdf: any) {
    // 只有第一页加载时设置总页数
    if (page === 1) {
        state.numPages = pdf.numPages;
        // 如果初始加载的页面数超过了总页数，则调整为总页数
        if (state.loadedPages > state.numPages) {
            state.loadedPages = state.numPages;
        }
    }
}

function close() {
    // 内置关闭逻辑
    showPopup.value = false;
}

defineExpose({
    open
});
function download() {
    emit('download');
}
</script>

<style scoped>
.pdf-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.pdf-preview {
    flex: 1;
    margin-top: 10px;
    padding: 0;
    box-sizing: border-box;
    background-color: #fff;
}

.pdf-wrap {
    overflow-y: auto;
    height: 100%;
    max-height: calc(100vh - 150px);
}

.vue-pdf-embed {
    text-align: center;
    width: 100%;
    border: 1px solid #e5e5e5;
    margin: 0 auto;
    box-sizing: border-box;
}

.multi-page {
    margin-bottom: 20px;
}

.page-tool {
    padding-left: 10px;
    padding-right: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgb(66, 66, 66);
    color: white;
    border-radius: 19px;
    margin: 10px;
}

.page-tool-item {
    padding: 10px 0;
    width: 20%;
    text-align: center;
    cursor: pointer;
}

.pdf-viewer-header {
    position: sticky;
    top: 0;
    z-index: 10;
}

.multi-page-container {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.pdf-wrap {
    overflow-y: auto;
    height: 100%;
}
</style>